# -*- coding: utf-8 -*-

import json
from tencentcloud.common import credential
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.ocr.v20181119 import ocr_client, models
from typing import Dict


class TencentOCR(object):

    def __init__(self):
        SecretId = "AKIDFMH1YqunSs42lGYcT7WgiW6Rm9PJ6g2D"
        SecretKey = "2tVt2wc5PXQ5VgdLq7AzZu2vZy83jARV"
        cred = credential.Credential(SecretId, SecretKey)

        httpProfile = HttpProfile()
        httpProfile.endpoint = "ocr.tencentcloudapi.com"

        clientProfile = ClientProfile()
        clientProfile.httpProfile = httpProfile
        self.client = ocr_client.OcrClient(cred, "", clientProfile)

    def general_ocr(self, image_url: str) -> Dict:
        """通用文字识别"""
        req = models.GeneralBasicOCRRequest()
        params = {
            "ImageUrl": image_url
        }
        req.from_json_string(json.dumps(params))

        resp = self.client.GeneralBasicOCR(req)
        data = json.loads(resp.to_json_string())
        return data

    def table_ocr(self, image_url: str) -> Dict:
        """表格OCR识别"""
        req = models.RecognizeTableOCRRequest()
        params = {
            "ImageUrl": image_url
        }
        req.from_json_string(json.dumps(params))

        resp = self.client.RecognizeTableOCR(req)
        data = json.loads(resp.to_json_string())
        return data

    def latex_ocr(self, image_url: str) -> Dict:
        """公式OCR识别"""
        req = models.FormulaOCRRequest()
        params = {
            "ImageUrl": image_url
        }
        req.from_json_string(json.dumps(params))

        resp = self.client.FormulaOCR(req)
        data = json.loads(resp.to_json_string())
        return data

    def invoice_ocr(self, image_url: str) -> Dict:
        """通用票据识别"""
        req = models.RecognizeGeneralInvoiceRequest()
        params = {
            "ImageUrl": image_url
        }
        req.from_json_string(json.dumps(params))

        resp = self.client.RecognizeGeneralInvoice(req)
        data = json.loads(resp.to_json_string())
        return data

    def vat_invoice_ocr(self, image_url: str) -> Dict:
        """增值税发票识别"""
        req = models.VatInvoiceOCRRequest()
        params = {
            "ImageUrl": image_url
        }
        req.from_json_string(json.dumps(params))
        resp = self.client.VatInvoiceOCR(req)
        data = json.loads(resp.to_json_string())
        return data


if __name__ == '__main__':
    tencent = TencentOCR()
    img_url = "https://pic1.zhimg.com/v2-6bd21c580cc979554f8fd02da7dd62fc_r.jpg"
    res = tencent.general_ocr(img_url)
    for item in res["TextDetections"]:
        print(item["DetectedText"])
